﻿Ext.define('App.desktop.DetailWindow', {
    extend: 'Ext.Window',
    requires: [
        'App.desktop.DetailView',
        'App.desktop.Workspace'
        ],
    closable: true,
    closeAction: 'hide',
    height: 500,
    width: 400,
    border: false,
    layout: 'fit',
    constrain: true,

    initComponent: function () {

        var me = this;

        var view =
        {
            xtype: 'detailView',
            itemId: 'detailView',
            entity: me.entity,
            child: me.child,
            operation: me.operation,
            identifiers: me.identifiers
        };

        me.items = [view];

        me.buttons = [
            {
                text: 'Reset',
                iconCls: 'icon-reset',
                handler: function () {

                    var f = me.getComponent('detailView');
                    f.getForm().reset();
                },
                scope: me
            },
            {
                text: 'Save',
                iconCls: 'icon-save',
                handler: me.saveEntity,
                scope: me
            },
            {
                text: 'Cancel',
                iconCls: 'icon-cancel',
                handler: function () { me.close(); },
                scope: me
            }
        ];

        me.callParent();
        me.refresh(me.operation, me.identifiers, me.callback);
    },

    getOperationLabel: function () {

        switch (this.operation) {
            case 'add': return 'Add';
            case 'view': return 'View';
            case 'edit': return 'Edit';
            default: return '';
        };
    },

    // Refreshes the form
    refresh: function (operation, identifiers, callback) {

        var me = this;
        var view = me.getComponent('detailView');
        me.operation = operation;
        me.identifiers = identifiers;
        me.callback = callback;

        var attributeName = me.attribute ? me.attribute.Name : null;

        if (me.operation == 'add') {

            me.identifiers = null; // They should be null for 'add' operation and they will be set by the loadForm function
            view.enableCCFields(false); // Disable links in form
            me.setWindowTitle(attributeName);
        }
        else {

            me.loadForm(attributeName, me.identifiers, function (response) {

                if (response.count == 0) {

                    me.operation = 'add';
                    view.enableCCFields(false); // Disable links in form
                }
                else {

                    me.operation = 'edit';
                    view.enableCCFields(true); // Enable links in form
                }

                me.setWindowTitle(attributeName);
            });
        }
    },

    setWindowTitle: function (attributeName) {

        var me = this;

        if (attributeName == null) {
            me.setTitle(me.entity.Name + ' - ' + me.getOperationLabel());
        }
        else {
            me.setTitle(me.entity.Name + '. ' + attributeName + '[' + me.child.Name + '] - ' + me.getOperationLabel());
        }
    },

    loadForm: function (attributeName, identifiers, callback) {

        var me = this;
        me.identifiers = identifiers;
        var f = me.getComponent('detailView');

        var url = attributeName != null ? '/Entity/GetComplexObject' : '/Entity/GetObject';

        f.getForm().load({
            url: url,
            params:
            {
                typeName: me.entity.FullName,
                attributeName: attributeName,
                identifiers: Ext.encode(App.desktop.Workspace.toArray(identifiers))
            },
            waitMsg: 'Loading...',
            success: function (form, action) {

                if (callback) {
                    callback(Ext.decode(action.response.responseText));
                }
            },
            failure: function (form, action) {

                var r = Ext.decode(action.response.responseText);
                App.desktop.Workspace.showError("Error loading form", r.msg);
            }
        });
    },

    saveEntity: function () {

        var me = this;
        var url = null;
        var entity = null;
        var attributeName = null;

        if (me.operation == 'add') {

            if (me.attribute == null) {

                url = '/Entity/Insert';
            }
            else { // We are setting either a complex object or adding a collection item

                attributeName = me.attribute.Name;
                var type = App.desktop.Workspace.getType(me.attribute.Category);

                if (type == 'collection') {

                    url = '/Entity/AddItem';
                }
                else { // complex

                    url = '/Entity/Set';
                }
            }
        }
        else { // update

            url = '/Entity/Update';

            if (me.attribute != null) {

                attributeName = me.attribute.Name;
            }
        }

        var f = this.getComponent('detailView');

        f.getForm().submit({
            url: url,
            method: 'POST',
            params:
            {
                typeName: me.entity.FullName,
                attributeName: attributeName,
                identifiers: Ext.encode(Ext.decode(me.identifiers)) // To generate a valid JSON
            },
            waitMsg: 'Saving ...',
            success: function (form, action) {

                me.close();

                if (me.callback) {
                    me.callback();
                }
            },
            failure: function (form, action) {

                if (action.failureType == 'connect') {

                    App.desktop.Workspace.showError('Error saving form', 'Connection timeout');
                    return;
                }

                var r = Ext.decode(action.response.responseText);

                if (r.msg == 'Session expired') { // Log out the user if the session expired

                    App.desktop.Workspace.logOff();
                    return;
                }

                App.desktop.Workspace.showError('Error saving form', r.msg);
            }
        });
    }

});